using B.S.Medical.Api.Write.Application.Command.DoctorSchedule;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.Domain.Medical;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using System.Linq;

namespace B.S.Medical.Api.Write.Application.Handler.DoctorSchedule
{
    public class SetDoctorDayScheduleHandler : IRequestHandler<SetDoctorDayScheduleCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<DoctorScheduleModel> _scheduleRepo;
        private readonly IBaseRepository<registrationModel> _registrationRepo;
        private readonly IBaseRepository<DoctorModel> doctorRepo;

        public SetDoctorDayScheduleHandler(IBaseRepository<DoctorScheduleModel> scheduleRepo, IBaseRepository<registrationModel> registrationRepo,IBaseRepository<DoctorModel> doctorRepo)
        {
            _scheduleRepo = scheduleRepo;
            _registrationRepo = registrationRepo;
            this.doctorRepo = doctorRepo;
        }

        public async Task<ApiResult<bool>> Handle(SetDoctorDayScheduleCommand request, CancellationToken cancellationToken)
        {
            // 上午
            var amSchedule = _scheduleRepo.GetAll()
                .FirstOrDefault(s => s.DoctorId == request.DoctorId && s.ScheduleDate.Date == request.Date.Date && s.Period == 1);
            if (request.AM != null)
            {
                if (amSchedule == null)
                {
                    // 新增
                    amSchedule = new DoctorScheduleModel
                    {
                        DoctorId = request.DoctorId,
                        DepartmentId = doctorRepo.GetAll().FirstOrDefault(s => s.Id == request.DoctorId).DepartmentId,
                        ScheduleDate = request.Date.Date,
                        Period = 1,
                        IsAvailable = request.AM.IsAvailable,
                        StartTime = request.AM.StartTime,
                        EndTime = request.AM.EndTime,
                        SlotCount = request.AM.SlotCount
                    };
                    await _scheduleRepo.CreateAsync(amSchedule);
                }
                else
                {
                    // 修改
                    amSchedule.IsAvailable = request.AM.IsAvailable;
                    amSchedule.StartTime = request.AM.StartTime;
                    amSchedule.EndTime = request.AM.EndTime;
                    amSchedule.SlotCount = request.AM.SlotCount;
                    await _scheduleRepo.UpdateAsync(amSchedule);
                }
                // 处理号源表（上午）
                if (amSchedule.Id > 0)
                {
                    var amRegs = _registrationRepo.GetAll().Where(r => r.schedule_id == amSchedule.Id && !r.IsDeleted).ToList();
                    if (amRegs.Any())
                    {
                        foreach (var reg in amRegs)
                        {
                            reg.IsDeleted = true;
                            await _registrationRepo.UpdateAsync(reg);
                        }
                    }
                    int count = Math.Min(request.AM.SlotCount, 99);
                    for (int i = 1; i <= count; i++)
                    {
                        var reg = new registrationModel
                        {
                            schedule_id = amSchedule.Id,
                            slot_number = i,
                            status = 0,
                            IsDeleted = false
                        };
                        await _registrationRepo.CreateAsync(reg);
                    }
                }
            }

            // 下午
            var pmSchedule = _scheduleRepo.GetAll()
                .FirstOrDefault(s => s.DoctorId == request.DoctorId && s.ScheduleDate.Date == request.Date.Date && s.Period == 2);
            if (request.PM != null)
            {
                if (pmSchedule == null)
                {
                    // 新增
                    pmSchedule = new DoctorScheduleModel
                    {
                        DoctorId = request.DoctorId,
                        ScheduleDate = request.Date.Date,
                        DepartmentId = doctorRepo.GetAll().FirstOrDefault(s => s.Id == request.DoctorId).DepartmentId,
                        Period = 2,
                        IsAvailable = request.PM.IsAvailable,
                        StartTime = request.PM.StartTime,
                        EndTime = request.PM.EndTime,
                        SlotCount = request.PM.SlotCount
                    };
                    await _scheduleRepo.CreateAsync(pmSchedule);
                }
                else
                {
                    // 修改
                    pmSchedule.IsAvailable = request.PM.IsAvailable;
                    pmSchedule.StartTime = request.PM.StartTime;
                    pmSchedule.EndTime = request.PM.EndTime;
                    pmSchedule.SlotCount = request.PM.SlotCount;
                    await _scheduleRepo.UpdateAsync(pmSchedule);
                }
                // 处理号源表（下午）
                if (pmSchedule.Id > 0)
                {
                    var pmRegs = _registrationRepo.GetAll().Where(r => r.schedule_id == pmSchedule.Id && !r.IsDeleted).ToList();
                    if (pmRegs.Any())
                    {
                        foreach (var reg in pmRegs)
                        {
                            reg.IsDeleted = true;
                            await _registrationRepo.UpdateAsync(reg);
                        }
                    }
                    int count = Math.Min(request.PM.SlotCount, 99);
                    for (int i = 1; i <= count; i++)
                    {
                        var reg = new registrationModel
                        {
                            schedule_id = pmSchedule.Id,
                            slot_number = i,
                            status = 0,
                            IsDeleted = false
                        };
                        await _registrationRepo.CreateAsync(reg);
                    }
                }
            }

            return new ApiResult<bool> { Code = ApiEnum.Success, Data = true, Msg = "保存成功" };
        }
    }
}